<template>
  <div>
    <loader :loading="loading">
      <!-- 加载页面 -->
      <template slot="loader">
        <div>
          <ring-loading></ring-loading>
        </div>
      </template>
      <!-- 内容页面 -->
      <template slot="body">
        <!-- 文章详情 -->
        <div v-if="!$common.isEmpty(articleId)">
          <!-- 封面 -->
          <cover
            v-if="!$common.isEmpty(articleInfo)"
            :articleInfo="articleInfo"
          ></cover>
          <!-- 文章 -->
          <div class="bg" v-if="!$common.isEmpty(articleInfo)">
            <div class="article-container my-animation-slide-bottom">
              <!-- TODO 视频 -->
              <!--              <div style="margin-bottom: 20px">-->
              <!--                <videoPlayer url="" :cover="articleInfo.articleCover">-->
              <!--                </videoPlayer>-->
              <!--              </div>-->
              <!-- 文章内容 -->
              <div v-html="articleContentHtml" class="entry-content"></div>
              <!-- 最后更新时间 -->
              <div class="article-update-time">
                <span>文章最后更新于 {{ articleInfo.updateTime }}</span>
              </div>
              <!-- 分类 -->
              <div class="article-sort">
                <span
                  @click="
                    $router.push({
                      path: `/sort`,
                      query: {
                        sortId: articleInfo.sortResp.id,
                      },
                    })
                  "
                  >{{ articleInfo.sortResp.sortName }}</span
                >
              </div>
              <!-- 作者信息 -->
              <blockquote>
                <div>作者：{{ articleInfo.author }}</div>
                <div>
                  <span>版权&许可请详阅</span>
                  <span
                    style="color: #38f; cursor: pointer"
                    @click="copyrightDialogVisible = true"
                  >
                    版权声明
                  </span>
                </div>
              </blockquote>
            </div>
            <div id="toc" class="toc"></div>
          </div>

          <el-dialog
            title="版权声明"
            :visible.sync="copyrightDialogVisible"
            width="80%"
            :append-to-body="true"
            class="article-copy"
            center
          >
            <div
              style="display: flex; align-items: center; flex-direction: column"
            >
              <div class="copyright-container">
                <p>
                  {{ $store.state.system.webInfo.webName }}是指运行在{{
                    $constant.host
                  }}域名及相关子域名上的网站，本条款描述了{{
                    $store.state.system.webInfo.webName
                  }}网站的版权声明：
                </p>
                <ul>
                  <li>
                    本站仅供学习与参考，请勿使用于商业用途。如需用作商业用途，请务必与作者联系
                  </li>
                  <li>
                    本站提供的所有文章、展示的图片素材等内容部分来源于互联网平台，仅供学习参考。如有侵犯您的版权，请联系本站负责人，承诺将在三个工作日内改正。
                  </li>
                  <li>未经本站明确许可，任何人不得盗链本站资源</li>
                  <li>
                    本站不保证网站内容的全部准确性、安全性和完整性，请您在阅读、下载及使用过程中自行确认；且亦不承担上述资源对您造成的任何形式的损失或伤害。
                  </li>
                  <li>
                    本站中的文章/视频（包括转载文章/视频）的版权仅归原作者所有，若作者有版权声明或文章从其它网站转载而附带有原所有站的版权声明者，其版权归属以附带声明为准；文章仅代表作者本人的观点，与本站立场无关。
                  </li>
                </ul>
              </div>
            </div>
          </el-dialog>
        </div>
      </template>
    </loader>
  </div>
</template>

<script>
import cover from "./cover.vue";
import { getArticleById } from "@/api/article";
import MarkdownIt from "markdown-it";
import tocbot from "tocbot";

import ClipboardJS from "clipboard";
import loader from "@/components/common/loader.vue";
import ringLoading from "@/components/common/ringLoading.vue";
import videoPlayer from "@/components/common/videoPlayer.vue";

export default {
  components: {
    cover,
    loader,
    ringLoading,
    videoPlayer,
  },
  data() {
    return {
      loading: true,
      articleId: this.$route.params.articleId,
      // 文章信息
      articleInfo: {
        sortResp: {
          id: 30,
          sortName: "",
          sortDescription: "",
          labelNum: null,
          articleNum: null,
          priority: null,
        },
      },
      // 解析后的文章内容
      articleContentHtml: "",
      // 版权声明弹窗
      copyrightDialogVisible: false,
    };
  },
  created() {
    this.getArticle();
  },
  mounted() {
    window.addEventListener("scroll", this.onScrollPage);
  },
  destroyed() {
    window.removeEventListener("scroll", this.onScrollPage);
  },
  methods: {
    getArticle() {
      if (this.$common.isEmpty(this.articleId)) {
        this.$router.push({ path: "/" });
      }
      getArticleById(this.articleId)
        .then((res) => {
          this.articleInfo = res.data;
          if (this.$common.isEmpty(this.articleInfo)) {
            this.$router.push({ path: "/" });
          }
          const md = new MarkdownIt({ breaks: true }).use(
            require("markdown-it-multimd-table")
          );
          this.articleContentHtml = md.render(this.articleInfo.articleContent);
          this.$nextTick(() => {
            // 图片展示
            this.$common.imgShow(".entry-showContent img");
            // 代码高亮
            this.highlight();
            this.addId();
            this.getTocbot();
          });
          this.loading = false;
        })
        .catch((error) => {
          this.$message({
            type: "warning",
            message: "文章不存在或已下架！！",
          });
        });
    },
    onScrollPage() {
      this.scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      if (this.scrollTop < window.innerHeight / 4) {
        $(".toc").css("top", window.innerHeight / 4);
      } else {
        $(".toc").css("top", "90px");
      }
    },
    getTocbot() {
      tocbot.init({
        tocSelector: "#toc",
        contentSelector: ".entry-showContent",
        headingSelector: "h1, h2, h3, h4, h5,h6",
        scrollSmooth: true,
        fixedSidebarOffset: "auto",
        scrollSmoothOffset: -100,
        hasInnerContainers: false,
      });
    },
    addId() {
      let headings = $(".entry-showContent").find("h1, h2, h3, h4, h5, h6");
      headings.attr("id", (i, id) => id || "toc-" + i);
    },
    highlight() {
      let attributes = {
        autocomplete: "off",
        autocorrect: "off",
        autocapitalize: "off",
        spellcheck: "false",
        contenteditable: "false",
      };

      $("pre").each(function (i, item) {
        let preCode = $(item).children("code");
        let classNameStr = preCode[0].className;
        let classNameArr = classNameStr.split(" ");

        let lang = "";
        classNameArr.some(function (className) {
          if (className.indexOf("language-") > -1) {
            lang = className.substring(
              className.indexOf("-") + 1,
              className.length
            );
            return true;
          }
        });

        // 检测语言是否存在，不存在则自动检测
        let language = hljs.getLanguage(lang.toLowerCase());
        if (language === undefined) {
          // 启用自动检测
          let autoLanguage = hljs.highlightAuto(preCode.text());
          preCode.removeClass("language-" + lang);
          lang = autoLanguage.language;
          if (lang === undefined) {
            lang = "java";
          }
          preCode.addClass("language-" + lang);
        } else {
          lang = language.name;
        }

        $(item).addClass("highlight-wrap");
        $(item).attr(attributes);
        preCode
          .attr("data-rel", lang.toUpperCase())
          .addClass(lang.toLowerCase());
        // 启用代码高亮
        hljs.highlightBlock(preCode[0]);
        // 启用代码行号
        hljs.lineNumbersBlock(preCode[0]);
      });

      $("pre code").each(function (i, block) {
        $(block).attr({
          id: "hljs-" + i,
        });

        $(block).after(
          '<a class="copy-code" href="javascript:" data-clipboard-target="#hljs-' +
            i +
            '"><i class="fa fa-clipboard" aria-hidden="true"></i></a>'
        );
        new ClipboardJS(".copy-code");
      });

      if ($(".entry-showContent").children("table").length > 0) {
        $(".entry-showContent")
          .children("table")
          .wrap("<div class='table-wrapper'></div>");
      }
    },
  },
  watch: {
    scrollTop(scrollTop) {
      let isShow = scrollTop - window.innerHeight > 30;
      if (isShow) {
        $("#toc-button").css("bottom", "14.1vh");
      } else {
        $("#toc-button").css("bottom", "8vh");
      }
    },
  },
};
</script>

<style scoped>
.bg {
  background-image: url();
}

.article-info i {
  margin-right: 6px;
}

.article-info span:not(:last-child) {
  margin-right: 5px;
}

.article-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 40px 20px;
}

.article-update-time {
  color: var(--greyFont);
  font-size: 12px;
  margin: 20px 0;
  user-select: none;
}

blockquote {
  line-height: 2;
  border-left: 0.2rem solid var(--blue);
  padding: 10px 1rem;
  background-color: var(--azure);
  border-radius: 4px;
  margin: 0 0 40px 0;
  user-select: none;
  color: var(--black);
}

.article-sort {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.article-sort span {
  padding: 3px 10px;
  background-color: var(--themeBackground);
  border-radius: 5px;
  font-size: 14px;
  color: var(--white);
  transition: all 0.3s;
  margin-right: 25px;
  cursor: pointer;
  user-select: none;
}

.article-sort span:hover {
  background-color: var(--red);
}

.article-like {
  color: var(--red) !important;
}

.article-like-icon {
  font-size: 60px;
  cursor: pointer;
  color: var(--greyFont);
  transition: all 0.5s;
  border-radius: 50%;
  margin-bottom: 20px;
}

.article-like-icon:hover {
  transform: rotate(360deg);
}

.process-wrap {
  margin: 0 0 40px;
}

.process-wrap hr {
  position: relative;
  margin: 10px auto 60px;
  border: 2px dashed var(--lightGreen);
  overflow: visible;
}

.process-wrap hr:before {
  position: absolute;
  top: -14px;
  left: 5%;
  color: var(--lightGreen);
  content: "❄";
  font-size: 30px;
  line-height: 1;
  transition: all 1s ease-in-out;
}

.process-wrap hr:hover:before {
  left: calc(95% - 20px);
}

.process-wrap >>> .el-collapse-item__header {
  border-bottom: unset;
  font-size: 20px;
  background-color: var(--background);
  color: var(--lightGreen);
}

.process-wrap >>> .el-collapse-item__wrap {
  background-color: var(--background);
}

.process-wrap .el-collapse {
  border-top: unset;
  border-bottom: unset;
}

.process-wrap >>> .el-collapse-item__wrap {
  border-bottom: unset;
}

.password-content {
  font-size: 13px;
  color: var(--maxGreyFont);
  line-height: 1.5;
}

#toc-button {
  position: fixed;
  right: 3vh;
  bottom: 8vh;
  animation: slide-bottom 0.5s ease-in-out both;
  z-index: 100;
  cursor: pointer;
  font-size: 23px;
  width: 30px;
}

#toc-button:hover {
  color: var(--themeBackground);
}

.copyright-container {
  color: var(--black);
  line-height: 2.5;
  padding: 0 30px 10px;
  font-size: 16px;
}

@media screen and (max-width: 700px) {
  .article-info-container {
    left: 20px;
    max-width: 320px;
  }

  .article-info-news {
    right: 20px;
  }
}

@media screen and (max-width: 400px) {
  #toc-button {
    right: 0.5vh;
  }
}
</style>
